<template>
  <div>
    <myDivider name="机关管理"></myDivider>
    <div class="Top">
      <el-input style="width: 160px;margin-left: 10px;" v-model="key1" placeholder="根据机关名称搜索"
        @keyup.enter.native="SouSuo" clearable></el-input>
      <el-input style="width: 160px" v-model="key2" placeholder="根据负责人姓名搜索" @keyup.enter.native="SouSuo"
        clearable></el-input>
      <el-input style="width: 160px" v-model="key3" placeholder="根据手机号码搜索" @keyup.enter.native="SouSuo"
        clearable></el-input>
      <el-cascader change-on-select clearable ref="areas" v-model="key4" :props="keyProps" @change="cascaderChange"
        style="width: 300px"></el-cascader>
      <el-button type="primary" style="margin-top: 20px; margin-left: 15px" @click="SouSuo">查询</el-button>
      <el-button style="margin-top: 20px; margin-left: 15px" @click="reset">重置</el-button>
      <div class="operation" v-if="permissionBtnShow">
        <el-button type="primary" @click="openForm" v-permission="'新增'">新增</el-button>
        <el-button icon="el-icon-files" @click="ToBatchImport" v-permission="'批量导入'">批量导入</el-button>
      </div>
    </div>

    <div>
      <el-table :data="userData" style="width: 100%;margin-top: 100px;" class="menuTable" row-key="uid"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">


        <el-table-column prop="name" label="机关名称" align="center" width="200px">
        </el-table-column>

        <el-table-column prop="responsiblePersonName" width="100px" label="负责人" align="center">
        </el-table-column>

        <el-table-column prop="telephoneNumber" label="手机号码" align="center" width="150px">
          <template slot-scope="scope">
            <span>{{ scope.row.telephoneNumber == null || scope.row.telephoneNumber == '' ? '—' :
        scope.row.telephoneNumber }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="areaName" label="详细地址" align="center">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="getPosition(scope.row)" placement="top-start">
              <span>{{
        getPosition(scope.row).length > 7 ?
          "..." + getPosition(scope.row).substring(getPosition(scope.row).length - 7,
            getPosition(scope.row).length) : getPosition(scope.row) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="address" label="详细地址" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.address == null || scope.row.address == '' ? '—' :
        scope.row.address }}</span>
          </template>
        </el-table-column> -->

        <el-table-column prop="" width="140px" label="级别" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.level == 1 ? '一级机关' : scope.row.level == 2 ? '二级机关' : scope.row.level == 3 ? '三级机关' : ''
              }}</span>

          </template>
        </el-table-column>

        <el-table-column prop="fatherAgencyName" label="上级机关" align="center" width="200px">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="scope.row.fatherAgencyName" placement="top-start">
              <span>{{ scope.row.fatherAgencyName == null || scope.row.fatherAgencyName == '' ? '—' :
        scope.row.fatherAgencyName }}</span>
            </el-tooltip>
          </template>
        </el-table-column>



        <el-table-column prop="createTime" label="创建时间" align="center" width="100px">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime ? scope.row.createTime.slice(0, 10) : '-' }}</span>
          </template>
        </el-table-column>


        <!-- <el-table-column prop="areaName" label="地址">
            <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="scope.row.areaName" placement="top-start">
              <span>{{ scope.row.areaName == null || scope.row.areaName == '' ? '—' :
                scope.row.areaName.length > 7 ?
                  "..." + scope.row.areaName.substring(scope.row.areaName.length - 7,
                    scope.row.areaName.length) : scope.row.areaName }}</span>
            </el-tooltip>
          </template>
          </el-table-column> -->

        <el-table-column label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <div v-if="permissionBtnShow" class="textBtn">
              <el-row>
                <el-col class="el" :span="8">
                  <span style="color: #5fadff;cursor: pointer;font-weight: 600;"
                    @click="openDetailPage(scope.row)">详情</span>
                </el-col>
                <el-col v-permission="'编辑'" class="el" :span="8">
                  <span style="color: #5fadff;cursor: pointer;font-weight: 600;"
                    @click="echoValueForUpdate(scope.row)">编辑</span>
                </el-col>
                <el-col v-permission="'删除'" class="el" :span="8">
                  <span style="color: #5fadff;cursor: pointer;font-weight: 600;"
                    @click="deleteAgencyById(scope.row)">删除</span>
                </el-col>
              </el-row>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页器 -->
    <myPagination :total="totalSize" :pageNum="pageNum" @PageChange="PageChange" @pageSizeChange="pageSizeChange">
    </myPagination>

    <!-- <div class="pageFooterFather">
        <el-pagination v-if="totalSize > pageSize" background layout="prev, pager, next" :total="totalSize"
          @current-change="handleCurrentChange" class="pageFooter">
        </el-pagination>
      </div> -->
  </div>
</template>





<script>

import {
  getAgencyList,
  deleteAgencyInformation,
  getcityList
} from "./agency";
import { timeYMD } from "@/utils/utils.js";

export default {
  data() {
    return {
      permissionBtnShow: false,
      keyProps: {
        lazy: true,
        lazyLoad(node, resolve) {
          let { level } = node
          if (node.level == 0) {
            getcityList('000000').then(res => {
              res.forEach(el => {
                el.value = el.criCode
                el.label = el.criName
                el.leaf = level >= 3
              })
              resolve(res)
            })
          } else {
            if (level == 3) {
              resolve([])
            } else {
              getcityList(node.value).then(res => {
                res.forEach(el => {
                  el.value = el.criCode
                  el.label = el.criName
                  el.leaf = level >= 2
                })
                resolve(res)
              })
            }

          }

        }
      },
      userData: [], //用户数据
      depmentManageData: [],
      allRoleListData: [],
      key1: '',
      key2: '',
      key3: '',
      key4: [],
      insertForm: {
        // 新增弹框参数
        account: "",
        userName: "",
        status: "1",
        insertType: 0,

      },
      insertRules: {
        userName: [
          {
            required: true,
            message: "用户名称不能为空",
            trigger: "blur",
          },
        ],
        account: [
          {
            required: true,
            message: "用户账号不能为空",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "用户密码不能为空",
            trigger: "blur",
          },
        ],
      },
      dialogFormVisible: false, //控制弹框开关
      formLabelWidth: "120px", //控制前面label的宽度
      pageNum: 1,
      pageSize: 10,
      totalSize: 0,
      props: {
        label: 'name',
        children: 'children',
        multiple: true
      },
      criLevel: 0,
    };
  },
  activated() {
    this.permissionBtnShow = false
    setTimeout(() => {
      this.permissionBtnShow = true
    }, 50)


    this.criLevel = 0
    let userData = JSON.parse(sessionStorage.getItem('logOnUser'))

    this.key1 = ''
    this.key2 = ''
    this.key3 = ''
    this.key4 = []
    //刚进入页面加载
    this.getAgencyList();
  },

  methods: {
    ToBatchImport() {
      this.$router.push('/batchImport?name=机关信息导入')
    },
    cascaderChange(val) {

      if (val.length == 0) {
        this.criLevel = 0
        this.SouSuo()
        return
      }
      this.$nextTick(() => {
        const checkedNodes = this.$refs['areas'].getCheckedNodes()
        const pathLabels = checkedNodes[0].level
        this.criLevel = pathLabels
        this.SouSuo()
        const dom = document.getElementsByClassName("el-radio is-checked");
        //这里我把dom打出来看了 最后一个选项才是我选中的节点 即[length-1] 有的博主写的是 第一个元素 即[0] 大家自行尝试
        let radioDom = dom[dom.length - 1];
        const brother = radioDom.nextElementSibling;
        brother.click();
      });
    },
    getPosition(val) {
      let areaName = val.areaName
      let address = val.address
      if (!val.areaName) areaName = ''
      if (!val.address) address = ''
      return (areaName + address)
    },
    pageSizeChange(e) {
      this.pageNum = 1
      this.pageSize = e
      this.getAgencyList()
    },
    PageChange(e) {

      this.pageNum = e
      this.getAgencyList()
    },
    SouSuo() {
      this.pageNum = 1
      this.getAgencyList()
    },
    reset() {
      this.key1 = ''
      this.key2 = ''
      this.key3 = ''
      this.key4 = []
      this.criLevel = 0
      this.pageNum = 1
      this.SouSuo()
    },
    //按条件查询菜单列表
    getAgencyList() {
      if (this.key4.length == 0) {
        this.key4 = ['']
      }
      let logOnUser = JSON.parse(sessionStorage.getItem('logOnUser'))
      getAgencyList({
        name: this.key1,
        pid: '',
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        "responsiblePersonName": this.key2,
        "telephoneNumber": this.key3,
        "criCode": this.key4[this.key4.length - 1],
        "criLevel": this.criLevel,
        unitId:logOnUser.unitId,
        unitType:logOnUser.unitType,
      }
      ).then((res) => {
        console.log(res, '列表数据')
        this.userData = res.list;
        // 遍历数据 如果数据为空就换为-
        // this.userData.forEach(el => {
        //   for(let item in el){
        //     if(el[item]=='' || el[item]==null){
        //       el[item] = '-'
        //     }
        //   }
        // });

        this.totalSize = res.total;

        
      });
    },


    //弹出弹框并加载父级菜单
    openForm() {
      this.$router.push({ path: '/agency/agencyInsert' });

    },


    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this.queryUserList();
    },
    forceChange() {
      this.$forceUpdate()
    },



    deleteAgencyById(row) {
      this.$confirm("确认删除该信息吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        var id = row.id;
        deleteAgencyInformation(id).then((res) => {
          if (res.code == 200) {
            this.$message({
              message: "删除成功",
              type: "success",
            });
            this.$nextTick(() => {
              this.getAgencyList();
            })
          } else {
            this.$message({
              message: res.message,
              type: "warning",
            });
          }
        });

      }).catch(() => {

        return;
      });
    },

    resetField() {
      this.insertForm.id = 0;
      this.dialogFormVisible = true;
      this.insertForm.userName = "";
      this.insertForm.gender = "0";
      this.insertForm.mobile = "";
      this.insertForm.email = "";
      this.insertForm.depId = "";
      this.insertForm.roleIds = [];
    },


    timeFormat(time) {
      return timeYMD(time);
    },

    echoValueForUpdate(row) {
      var id = row.id;
      this.$router.push({ path: '/agency/agencyInsert', query: { id: id, operateType: 'update' } })
    },


    //打开账号绑定窗口 并回显账号信息
    openBindingForm(row) {
      var id = row.id;
      this.$router.push({ path: '/agency/agencyBinding', query: { id: id, operateType: 'binding' } });
    },
    //打开账号绑定窗口 并回显账号信息
    openDetailPage(row) {
      var id = row.id;
      this.$router.push({ path: '/agency/agencyDetail', query: { id: id, operateType: 'binding' } });
    },


  },
};
</script>
<style scoped lang="less">
.textBtn {
  position: relative;

  /deep/ .el-row {
    display: flex;
    justify-content: center;
  }

  .el {
    display: block;
    position: relative;

    &:nth-child(n+2) {
      &::after {
        position: absolute;
        left: -1px;
        top: 50%;
        content: '';
        width: 2px;
        transform: translateY(-50%) scale(0.5, 1);
        height: 10px;
        background-color: #aaa;
      }
    }
  }
}




.Top {
  position: relative;

  .operation {
    position: absolute;
    left: 15px;
    top: 68px;
  }
}
</style>